# -*- coding: utf-8 -*-
# @Time : 2024/3/5 22:05
# @Author : TH
# Description:数据库连接封装
import pymysql


class DataBaseConnect:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None

    # 连接mysql数据库
    def connect(self):
        self.connection = pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database
        )

    # 查询数据
    def query(self, sql, params=None):
        if self.connection is None:
            self.connect()

        cursor = self.connection.cursor()
        cursor.execute(sql, params)
        return cursor.fetchall()

    def close(self):
        if self.connection is not None:
            self.connection.close()
            self.connection = None


if __name__ == '__main__':
    # 创建数据库连接
    db = DataBaseConnect("localhost", "username", "password", "database_name")
    # 执行查询
    result = db.query("SELECT * FROM table_name")
    print(result)

    # 关闭连接
    db.close()